package algorithm.graph;

import java.io.File;
import java.lang.reflect.Constructor;
import java.nio.file.Files;
import java.util.List;

public class ReadGraph {


    public static <T extends Graph> Graph readGraph(Class<T> clz, String fileName) {
        try {
            File file = new File(ReadGraph.class.getResource("/graph").getFile(), fileName);
            List<String> lines = Files.readAllLines(file.toPath());
            String s = lines.get(0);
            String[] split = s.split("\\s+");
            Constructor<T> constructor = clz.getConstructor(int.class, boolean.class);
            T graph = constructor.newInstance(Integer.valueOf(split[0]).intValue(), false);
            for (int i = 1; i < lines.size(); i++) {
                String[] arr = lines.get(i).split("\\s+");
                graph.addEdge(Integer.valueOf(arr[0]), Integer.valueOf(arr[1]));
            }
            return graph;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {

        // 使用两种图的存储方式读取testG1.txt文件
        String filename = "testG1.txt";

        Graph g1 = ReadGraph.readGraph(SparseGraph.class, filename);
        System.out.println("test G1 in Sparse Graph:");
        g1.show();

        System.out.println("=========================================");

        Graph g2 = ReadGraph.readGraph(DenseGraph.class, filename);
        System.out.println("test G1 in Dense Graph:");
        g2.show();

        System.out.println("=========================================");


        // 使用两种图的存储方式读取testG2.txt文件
        filename = "testG2.txt";
        Graph g3 = ReadGraph.readGraph(SparseGraph.class, filename);
        System.out.println("test G2 in Sparse Graph:");
        g3.show();

        System.out.println("=========================================");

        Graph g4 = ReadGraph.readGraph(DenseGraph.class, filename);
        System.out.println("test G2 in Dense Graph:");
        g4.show();
    }


}
